package com.ws.universal.tools.utils;

import android.content.Context;
import android.os.Environment;

import com.ws.universal.tools.utils.cache.FilePathUtils;

import java.io.File;

/**
 * @author:ws
 * @date: 2021/7/29 15:01
 * @desc 清除数据管理类 一般用于设置页面
 */
public final class DataCleanManager {
    private static final String TAG = "DataCleanManager";


    public static String getTotalCacheSize(Context context) throws Exception {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(FilePathUtils.getInstance().getCache());

        }
        return FilePathUtils.getInstance().formatSize(cacheSize);
    }

    //删除内外缓存
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(FilePathUtils.getInstance().getCache());
        }
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }


    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }
}
